package com.example.thread;

import com.example.entity.Host;
import server.HttpProtocolUtil;
import server.HttpServlet;
import server.Request;
import server.Response;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

/**
 * 1、先根据 域名获取 当前域名下的所配置的所有项目 servletMapperMap 集合
 * 2、在根据url 路径进行进行 url 字符转换、根据'/' 进行分割
 * 3、根据url 获取 到 项目名称，从servletMapperMap 获取指定项目下封装的 URL、servlet map集合 servletMap 集合
 * 4、根据url 获取 请求路径，从servletMap 查找对应 servlet处理类
 * 5、如果servletMap 没有对应的处理类，默认为当前请求为请求静态资源，获取静态资源 通过 webapps项目根目录和url 结合去指定位置获取静态文件内容
 * 6、对于没有相应资源的处理统一进行404 返回
 *
 * @author kangshuai
 */
public class RequestProcessor4 extends Thread {


    private Socket socket;

    private Map<String, Host> hostMap;

    public RequestProcessor4(Socket socket, Map<String, Host> hostMap) {
        this.socket = socket;
        this.hostMap = hostMap;
    }

    @Override
    public void run() {
        try {

            InputStream inputStream = socket.getInputStream();
            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            Host hostContext = hostMap.get(request.getHost());

            if (hostContext == null) {
                response.output(HttpProtocolUtil.getHttpHeader404());
            }

            Map<String, Map<String, HttpServlet>> servletMapperMap = hostContext.getMap();

            String[] urlArray = request.getUrl().replace("\\\\", "/").split("/");
            Map<String, HttpServlet> httpServletMap = servletMapperMap.get(urlArray[1]);

            if (httpServletMap == null) {
                response.output(HttpProtocolUtil.getHttpHeader404());
            }
            int urlLength = urlArray[0].length() + 1 + urlArray[1].length();
            HttpServlet httpServlet = httpServletMap != null ? httpServletMap.get(request.getUrl().substring(urlLength)) : null;


            // 静态资源处理
            if (httpServlet == null) {
                response.outputHtml(hostContext.getAppBase() + request.getUrl());
            } else {
                // 动态资源servlet请求
                httpServlet.service(request, response);
            }
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
